package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultList;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;

import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.PostService;
import com.fz.us.admin.company.service.PowerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器 - 职权信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-11 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/power")
public class PowerController extends BaseController {

    private static final long serialVersionUID = 212576765234743317L;

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PostService postService;
    @Autowired
    private PowerService powerService;

    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user, Model model,
                         @RequestParam(required = false) String departmentId) {

        model.addAttribute("departmentId", departmentId);
        return "/main/company/power_input";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {

        model.addAttribute("keyId", keyId);
        return "/main/company/power_input";
    }



    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String departmentId,
                       String postId,
                       @RequestParam(required = false) String parentId,
                       Power power) {
        // 必填校验
        if (StringUtils.isBlank(departmentId)) {
            return resultService.fail("部门不能为空");
        }
        if (StringUtils.isBlank(postId)) {
            return resultService.fail("岗位不能为空");
        }
        // 部门
        Department department = departmentService.get(departmentId);
        if (department != null) {
            power.setDepartment(department);
        }
        // 岗位
        Post post = postService.get(postId);
        if (post != null) {
            power.setPost(post);
        }
        // 上级职权
        if (StringUtils.isNotBlank(parentId)) {
            Power parent = powerService.get(parentId);
            if (parent != null) {
                power.setParent(parent);
            }
        }

        if (StringUtils.isBlank(keyId)) {// 保存
            return ajaxJson(powerService.createEntity(user, power));
        } else {// 修改
            return ajaxJson(powerService.updateEntity(user, keyId, power));
        }
    }

    /**
     * 初始化表单
     */
    @RequestMapping(value = "init", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object init(@CurrentUser User user,
                       @RequestParam(required = false) String departmentId) {
        Power power = new Power();
        if (StringUtils.isNotBlank(departmentId)) {
            Department department = departmentService.get(departmentId);
            if (department != null) {
                power.setDepartment(department);
            }
        }

        Map<String, Object> dataMap = powerService.getDetailMap(power);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 获取详情
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object read(@CurrentUser User user,
                       @PathVariable String keyId) {
        Power power = powerService.get(keyId);
        if (power == null){
            power = new Power();
        }

        Map<String, Object> dataMap = powerService.getDetailMap(power);

        Result result = resultService.success("", dataMap);

        return ajaxJson(result);
    }

    /**
     * 操作
     */
    @RequestMapping(value = "method/{method}/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String method,
                         @PathVariable String keyId) {
        Result result = powerService.methodEntity(user, method, keyId);

        return ajaxJson(result);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list_department", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list_department(@CurrentUser User user,
                                               String departmentId,
                                               JqGridPager pager,
                                               @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        Department department = null;
        if(StringUtils.isNotEmpty(departmentId)){
            department = departmentService.get(departmentId);
        }
        // 排序
        /*
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);*/
//        SearchResultPaging searchResult = powerService.pagingAllPower(PageHelp.page(pager.getPage(), pager.getRows()), rules, order, company, department, BaseEnumManager.StateEnum.Enable);
        SearchResultPaging searchResult = powerService.pagingPower(null,null,null, company, department, BaseEnumManager.StateEnum.Enable);

        List<Power> powerList = searchResult.getList();

        List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Power entity : powerList) {
            Map<String, Object> map = powerService.getListMap(entity);
            dataRows.add(map);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list_select", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object list_select(@CurrentUser User user,
                              String departmentId) {
        Company company = user.getCompany();

        Department department = departmentService.get(departmentId);

        SearchResultList searchResult = powerService.listPower(null, null, company, department, null, BaseEnumManager.StateEnum.Enable);

        List<Power> powerList = searchResult.getList();

        List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();

        for (Power entity : powerList) {
            Map<String, Object> map = powerService.getListMap(entity);
            dataRows.add(map);
        }

        return ajaxJson(resultService.successWithData(dataRows));
    }

    /**
     * tree
     */
    @RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Map<String, Object>> tree(@CurrentUser User user,
                                          @RequestParam(required = false) String id) {
        Company company = user.getCompany();

        List<Power> powerList = null;
        if (StringUtils.isBlank(id)) {
            powerList = powerService.getRootPowers(company);
        } else {
            Power power = powerService.get(id);
            if (power != null) {
                powerList = powerService.getPowers(company, power);
            }
        }
        if (powerList == null) {
            powerList = new ArrayList<Power>();
        }

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (Power power : powerList) {
            Map<String, Object> map = powerService.getTreeMap(power);

            mapList.add(map);
        }

        return mapList;
    }

    /**
     * tree
     */
    @RequestMapping(value = "tree_level", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object tree_level(@CurrentUser User user,
                             @RequestParam(required = false) String departmentId,
                             @RequestParam(required = false) String powerId) {
        Company company = user.getCompany();

        Department department = null;
        Power power = null;
        if (StringUtils.isNotBlank(departmentId)) {
            department = departmentService.get(departmentId);
        }
        if (StringUtils.isNotBlank(powerId)) {
            power = powerService.get(powerId);
            department = power.getDepartment();
        }

        return ajaxJson(resultService.successWithData(powerService.getLevelTreeMapList(company, department, power)));
    }

    /**
     * 选择(多个)
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user,@RequestParam(required = false) String sids, Model model) {
        model.addAttribute("sids",sids);
        if (StringUtils.isNotBlank(sids)) {
            String[] pids = StringUtils.split(sids,",");
            ArrayList<Power> powers = new ArrayList<Power>();
            for (String pid : pids) {
                Power power = powerService.get(pid);
                powers.add(power);
            }
            model.addAttribute("selectedPowers",powers);
        }

        return "/main/company/power_dialogs";
    }

}
